<template>
  <Modal
    :open="open"
    :title="$t('daprplus.auth.user.setRoleTitle', { name: user.nickName })"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Form :model="roleForm" ref="roleFormRef" layout="vertical">
      <Form.Item :label="$t('daprplus.auth.user.roles')">
        <Checkbox.Group v-model:value="roleForm.roleNames" style="width: 100%">
          <div style="display: flex; flex-wrap: wrap; gap: 8px">
            <Checkbox
              v-for="role in roleOptions"
              :key="role.name"
              :value="role.name"
            >
              {{ role.name }}
            </Checkbox>
          </div>
        </Checkbox.Group>
      </Form.Item>
    </Form>
  </Modal>
</template>

<script lang="ts" setup>
import { Modal, Form, Checkbox, message } from 'ant-design-vue';
import { ref, reactive, defineProps, defineEmits, watch } from 'vue';
import { $t } from '@vben/locales';
import type { UserOutDto } from './user.vue';
import { setRoleApi, type SetRoleDto } from '#/api/daprplus/auth/user';
import { getRoleNodeApi, type RoleNodeDto } from '#/api/daprplus/auth/role';

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  user: {
    type: Object as () => UserOutDto,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:open', 'success']);

const confirmLoading = ref(false);
const roleFormRef = ref();
const roleForm = reactive({
  roleNames: [] as string[],
});
const roleOptions = ref<RoleNodeDto[]>([]);

// 处理取消按钮点击
function handleCancel() {
  emit('update:open', false);
}

// 加载角色列表
async function loadRoles() {
  try {
    const roles = await getRoleNodeApi(props.user.id);
    roleOptions.value = roles;

    // 设置已选中的角色
    roleForm.roleNames = roles
      .filter((role) => role.isSelected)
      .map((role) => role.name);
  } catch (error) {
    console.error('获取角色列表失败:', error);
    message.error($t('daprplus.auth.user.getRolesFailed'));
  }
}

// 监听模态框打开状态，当打开时加载角色列表
watch(
  () => props.open,
  (newVal) => {
    if (newVal) {
      loadRoles();
    }
  },
);

// 处理角色提交
async function handleSubmit() {
  if (!props.user || !props.user.id) return;

  try {
    confirmLoading.value = true;

    // 调用设置角色API
    const dto: SetRoleDto = {
      userId: props.user.id,
      roleNames: roleForm.roleNames,
    };

    await setRoleApi(dto);

    message.success($t('daprplus.auth.user.roleSetSuccess'));
    emit('update:open', false);
    emit('success');
  } catch (error) {
    console.error('角色设置失败:', error);
    message.error($t('daprplus.auth.user.roleSetFailed'));
  } finally {
    confirmLoading.value = false;
  }
}
</script>

<style scoped></style>
